<?php

namespace Admin\Controller;

use Think\Controller;
use Admin\Model\CpsModel;
use Think\Crypt;

class CpsController extends Controller {

    private $cpsModel;

    public function __construct() {
        parent::__construct();
        session("[start]");
        if (!isset($_SESSION['admininfo']) || $_SESSION['admininfo']['id'] < 1) {
            $this->redirect('Login/index');
        }
        $this->cpsModel = new CpsModel();
    }

    public function index() {
        //读取渠道及子渠道账号
        $list = $this->cpsModel->formatCpsMember();
        $this->assign('list', $list);
        $this->display();
    }

    public function post() {
        $id = intval($_REQUEST['id']);
        $username = $_POST['username'] ? I("post.username") : '';
        $password = $_POST['password'] ? I("post.password") : '';
        if (empty($id)) {
            if (IS_POST) {
                $data['username'] = $username;
                $data['password'] = Crypt::Crypt_Hash_Create($password);
                if ($this->cpsModel->add($data)) {
                    $this->success("账号添加成功", U("cps/index"));
                } else {
                    $this->error("账号添加失败", U("cps/index"));
                }
            }            //添加渠道号
        } else {
            //修改渠道号
            if (IS_POST) {
                $data['username'] = $username;
                if ($password != '') {
                    $data['password'] = Crypt::Crypt_Hash_Create($password);
                }
                if($this->cpsModel->where("id='%d'",$id)->save($data)){
                    $this->success("账号修改成功", U("cps/index"));
                }else{                    
                    $this->error("账号修改失败", U("cps/index"));
                }
            }
            $list = $this->cpsModel->where("id='%d'", $id)->find();
            $this->assign('id', $id);
            $this->assign('username', $list['username']);
        }
        $this->display();
    }

}
